package com.wust.modules.online.cgform.controller;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import com.google.common.collect.Lists;
import com.wust.modules.online.cgform.model.*;
import com.wust.modules.online.config.exception.BusinessException;
import com.wust.modules.online.config.exception.DBException;
import com.wust.modules.online.config.util.TableUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import com.wust.common.api.vo.Result;
import com.wust.common.system.api.SysBaseApi;
import com.wust.common.util.BrowserUtils;
import com.wust.common.util.SpringContextUtils;
import com.wust.common.util.TokenUtils;
import com.wust.common.util.oConvertUtils;
import com.wust.modules.online.cgform.converter.ConverterUtil;
import com.wust.modules.online.cgform.entity.OnlCgformEnhanceJs;
import com.wust.modules.online.cgform.entity.OnlCgformField;
import com.wust.modules.online.cgform.entity.OnlCgformHead;
import com.wust.modules.online.cgform.service.IOnlCgformFieldService;
import com.wust.modules.online.cgform.service.IOnlCgformHeadService;
import com.wust.modules.online.cgform.service.IOnlCgformBatchService;
import com.wust.modules.online.cgform.service.IOnlineService;
import com.wust.modules.online.cgform.util.EnhanceJsUtil;
import com.wust.modules.online.cgform.util.ExcelDataHandlerDefaultUtil;
import com.wust.modules.online.cgform.util.FilesGeneratedUtil;
import com.wust.modules.online.cgform.util.SqlSymbolUtil;
import com.wust.modules.poi.excel.ExcelExportUtil;
import com.wust.modules.poi.excel.ExcelImportUtil;
import com.wust.modules.poi.excel.entity.ExportParams;
import com.wust.modules.poi.excel.entity.ImportParams;
import com.wust.modules.poi.excel.entity.params.ExcelExportEntity;
import com.wust.modules.poi.handler.inter.IExcelDataHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer;
import org.springframework.jdbc.support.incrementer.PostgreSQLSequenceMaxValueIncrementer;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.apache.poi.ss.usermodel.Workbook;

/**
 * wanheng
 */
@Slf4j
@Api
@RestController("onlCgformApiController")
@RequestMapping({"/admin/cgform/api"})
public class OnlCgformApiController {

    @Resource
    private IOnlCgformHeadService onlCgformHeadService;

    @Resource
    private IOnlCgformFieldService onlCgformFieldService;

    @Resource
    private IOnlCgformBatchService onlCgformSqlService;

    @Resource
    private SysBaseApi sysBaseAPI;

    @Resource
    private IOnlineService onlineService;

    @Value("${online.path.upload}")
    private String upLoadPath;

    @Value("${online.uploadType}")
    private String uploadType;

    @PostMapping({"/addAll"})
    public Result<?> addAll(@RequestBody OnlCgformHeadModel onlCgformHeadModel) {
        log.info("onlCgformHeadModel--->" + onlCgformHeadModel);
        try {
            String tableName = onlCgformHeadModel.getHead().getTableName();
            return TableUtil.isTableExist(tableName) ? Result.error("数据库表[" + tableName + "]已存在,请从数据库导入表单") : this.onlCgformHeadService.addAll(onlCgformHeadModel);
        } catch (Exception e) {
            log.error("OnlCgformApiController.addAll()发生异常：" + e.getMessage(), e);
            return Result.error("操作失败");
        }
    }

    @PutMapping({"/editAll"})
    public Result<?> editAll(@RequestBody OnlCgformHeadModel onlCgformHeadModel) {
        log.info("onlCgformHeadModel--->" + onlCgformHeadModel);
        try {
            return this.onlCgformHeadService.editAll(onlCgformHeadModel);
        } catch (Exception e) {
            log.error("OnlCgformApiController.editAll()发生异常：" + e.getMessage(), e);
            return Result.error("操作失败");
        }
    }

    @GetMapping({"/getColumns/{code}"})
    public Result<OnlineConfigModel> getColumns(@PathVariable("code") String code) {
        Result result = new Result();
        OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(code);
        if (onlCgformHead == null) {
            result.error500("实体不存在");
            return result;
        } else {
            OnlineConfigModel onlineConfigModel = this.onlineService.queryOnlineConfig(onlCgformHead);
            result.setResult(onlineConfigModel);
            return result;
        }
    }


    @GetMapping({"/getData/{code}"})
    public Result<Map<String, Object>> getData(@PathVariable("code") String code, HttpServletRequest request) {
        Result result = new Result();
        OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(code);
        if (onlCgformHead == null) {
            result.error500("实体不存在");
            return result;
        } else {
            try {
                String tableName = onlCgformHead.getTableName();
                Map map = SqlSymbolUtil.getParameterMap(request);
                Map map1 = this.onlCgformFieldService.queryAutolistPage(tableName, code, map, (List) null);
                this.recordsEnhance(onlCgformHead, map1);
                result.setResult(map1);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                result.error500("数据库查询失败，" + e.getMessage());
            }
            return result;
        }
    }

    @GetMapping({"/getFormItem/{code}"})
    public Result<?> getFormItem(@PathVariable("code") String code, HttpServletRequest request) {
        OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(code);
        if (onlCgformHead == null) {
            Result.error("表不存在");
        }

        Result result = new Result();
        OnlCgformEnhanceJs onlCgformEnhanceJs = this.onlCgformHeadService.queryEnhanceJs(code, "form");
        JSONObject jsonObject = this.onlineService.queryOnlineFormObj(onlCgformHead, onlCgformEnhanceJs);
        if (onlCgformHead.getTableType() == 2) {
            JSONObject jsonObject1 = jsonObject.getJSONObject("schema");
            String subTableStr = onlCgformHead.getSubTableStr();
            if (oConvertUtils.isNotEmpty(subTableStr)) {
                ArrayList arrayList = new ArrayList();
                String[] subTableStrs = subTableStr.split(",");
                int length = subTableStrs.length;

                for (int i = 0; i < length; ++i) {
                    String subTableStr1 = subTableStrs[i];
                    OnlCgformHead onlCgformHead1 = (OnlCgformHead) this.onlCgformHeadService.getOne((Wrapper) (new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, subTableStr1));
                    if (onlCgformHead1 != null) {
                        arrayList.add(onlCgformHead1);
                    }
                }

                if (arrayList.size() > 0) {
                    Collections.sort(arrayList, new Comparator<OnlCgformHead>() {

                        @Override
                        public int compare(OnlCgformHead onlCgformHead1, OnlCgformHead onlCgformHead2) {
                            Integer orderNum = onlCgformHead1.getTabOrderNum();
                            if (orderNum == null) {
                                orderNum = 0;
                            }

                            Integer orderNum1 = onlCgformHead2.getTabOrderNum();
                            if (orderNum1 == null) {
                                orderNum1 = 0;
                            }

                            return orderNum.compareTo(orderNum1);
                        }
                    });
                    Iterator iterator = arrayList.iterator();

                    while (iterator.hasNext()) {
                        OnlCgformHead onlCgformHead1 = (OnlCgformHead) iterator.next();
                        List availableFields = this.onlCgformFieldService.queryAvailableFields(onlCgformHead1.getId(), onlCgformHead1.getTableName(), (String) null, false);
                        EnhanceJsUtil.getJsFunction(onlCgformEnhanceJs, onlCgformHead1.getTableName(), availableFields);
                        JSONObject jsonObject2 = new JSONObject();
                        List disabledFields = this.onlCgformFieldService.queryDisabledFields(onlCgformHead1.getTableName());
                        if (1 == onlCgformHead1.getRelationType()) {
                            jsonObject2 = SqlSymbolUtil.getFiledJson(availableFields, disabledFields, (FieldModel) null);
                        } else {
                            jsonObject2.put("columns", SqlSymbolUtil.getColumns(availableFields, disabledFields));
                        }

                        jsonObject2.put("id", onlCgformHead1.getId());
                        jsonObject2.put("describe", onlCgformHead1.getTableTxt());
                        jsonObject2.put("key", onlCgformHead1.getTableName());
                        jsonObject2.put("view", "tab");
                        jsonObject2.put("order", onlCgformHead1.getTabOrderNum());
                        jsonObject2.put("relationType", onlCgformHead1.getRelationType());
                        jsonObject1.getJSONObject("properties").put(onlCgformHead1.getTableName(), jsonObject2);
                    }
                }
            }

            if (onlCgformEnhanceJs != null && oConvertUtils.isNotEmpty(onlCgformEnhanceJs.getCgJs())) {
                jsonObject.put("enhanceJs", EnhanceJsUtil.getCgJs(onlCgformEnhanceJs.getCgJs()));
            }
        }

        result.setResult(jsonObject);
        return result;
    }

    @GetMapping({"/getFormItemBytbname/{table}"})
    public Result<?> getFormItemBytbname(@PathVariable("table") String table, @RequestParam(name = "taskId", required = false) String taskId, HttpServletRequest request) {
        Result result = new Result();
        LambdaQueryWrapper<OnlCgformHead> onlCgformHeadLambdaQueryWrapper = new LambdaQueryWrapper();
        onlCgformHeadLambdaQueryWrapper.eq(OnlCgformHead::getTableName, table);
        OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getOne(onlCgformHeadLambdaQueryWrapper);
        if (onlCgformHead == null) {
            Result.error("表不存在");
        }

        JSONObject jsonObject = new JSONObject();
        //onlCgformHead.setTaskId(taskId);
        onlCgformHead.setTaskId(null);
        jsonObject.put("schema", this.onlCgformHeadService.queryFormItem(onlCgformHead));
        jsonObject.put("head", onlCgformHead);
        result.setResult(jsonObject);
        return result;
    }

    @GetMapping({"/getEnhanceJs/{code}"})
    public Result<?> getEnhanceJs(@PathVariable("code") String code, HttpServletRequest request) {
        String s = "";
        OnlCgformEnhanceJs onlCgformEnhanceJs = this.onlCgformHeadService.queryEnhanceJs(code, "form");
        if (onlCgformEnhanceJs != null && oConvertUtils.isNotEmpty(onlCgformEnhanceJs.getCgJs())) {
            s = EnhanceJsUtil.getJsFunction(onlCgformEnhanceJs.getCgJs(), (List) null);
        }

        return Result.ok(s);
    }

    @GetMapping({"/form/{code}/{id}"})
    public Result<?> getForm(@PathVariable("code") String code, @PathVariable("id") String id) {
        try {
            Map map = this.onlCgformHeadService.queryManyFormData(code, id);
            return Result.ok(SqlSymbolUtil.getValueType(map));
        } catch (Exception e) {
            log.error("Online表单查询异常：" + e.getMessage(), e);
            return Result.error("查询失败，" + e.getMessage());
        }
    }

    @GetMapping({"/subform/{table}/{mainId}"})
    public Result<?> subform(@PathVariable("table") String table, @PathVariable("mainId") String mainId) {
        try {
            Map map = this.onlCgformHeadService.querySubFormData(table, mainId);
            return Result.ok(SqlSymbolUtil.getValueType(map));
        } catch (Exception e) {
            log.error("Online表单查询异常：" + e.getMessage(), e);
            return Result.error("查询失败，" + e.getMessage());
        }
    }

    @GetMapping({"/subform/list/{table}/{mainId}"})
    public Result<?> subformList(@PathVariable("table") String table, @PathVariable("mainId") String mainId) {
        try {
            return Result.ok(this.onlCgformHeadService.queryManySubFormData(table, mainId));
        } catch (Exception e) {
            log.error("Online表单查询异常：" + e.getMessage(), e);
            return Result.error("查询失败，" + e.getMessage());
        }
    }

    @GetMapping({"/form/table_name/{tableName}/{dataId}"})
    public Result<?> formTableName(@PathVariable("tableName") String tableName, @PathVariable("dataId") String dataId) {
        try {
            LambdaQueryWrapper<OnlCgformHead> onlCgformHeadLambdaQueryWrapper = new LambdaQueryWrapper();
            onlCgformHeadLambdaQueryWrapper.eq(OnlCgformHead::getTableName, tableName);
            OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getOne(onlCgformHeadLambdaQueryWrapper);
            if (onlCgformHead == null) {
                throw new Exception("OnlCgform tableName: " + tableName + " 不存在！");
            } else {
                return this.getForm(onlCgformHead.getId(), dataId);
            }
        } catch (Exception e) {
            log.error("Online表单查询异常，" + e.getMessage(), e);
            return Result.error("查询失败，" + e.getMessage());
        }
    }

    @PostMapping({"/form/{code}"})
    public Result<String> postForm(@PathVariable("code") String code, @RequestBody JSONObject jsonObject, HttpServletRequest request) {
        Result result = new Result();

        try {
            String idWorkerId = SqlSymbolUtil.getIdWorkerId();
            jsonObject.put("id", idWorkerId);
            String token = TokenUtils.getTokenByRequest(request);
            this.onlCgformHeadService.saveManyFormData(code, jsonObject, token);
            result.setSuccess(true);
            result.setResult(idWorkerId);
        } catch (Exception e) {
            log.error("OnlCgformApiController.formAdd()发生异常：", e);
            result.setSuccess(false);
            result.setMessage("保存失败，" + SqlSymbolUtil.getMessage(e));
        }

        return result;
    }

    @PutMapping({"/form/{code}"})
    public Result<?> putForm(@PathVariable("code") String code, @RequestBody JSONObject jsonObject) {
        try {
            this.onlCgformHeadService.editManyFormData(code, jsonObject);
        } catch (Exception e) {
            log.error("OnlCgformApiController.formEdit()发生异常：" + e.getMessage(), e);
            return Result.error("修改失败，" + SqlSymbolUtil.getMessage(e));
        }

        return Result.ok("修改成功！");
    }

    @DeleteMapping({"/form/{code}/{id}"})
    public Result<?> deleteForm(@PathVariable("code") String code, @PathVariable("id") String id) {
        try {

            OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(code);
            if (onlCgformHead == null) {
                return Result.error("实体不存在");
            }
            if ("Y".equals(onlCgformHead.getIsTree())) {
                if (id.indexOf(",") > 0) {
                    if (onlCgformHead.getTableType() == 2) {
                        this.onlCgformFieldService.deleteAutoListMainAndSub(onlCgformHead, id);
                    } else {
                        String tableName = onlCgformHead.getTableName();
                        this.onlCgformFieldService.deleteAutoListById(tableName, id);
                    }
                } else {
                    this.onlCgformHeadService.deleteOneTableInfo(code, id);
                }
            }
        } catch (Exception e) {
            log.error("OnlCgformApiController.formEdit()发生异常：" + e.getMessage(), e);
            return Result.error("删除失败");
        }

        return Result.ok("删除成功!");
    }

    @DeleteMapping({"/formByCode/{code}/{id}"})
    public Result<?> deleteFormByCode(@PathVariable("code") String code, @PathVariable("id") String id) {
        try {
            OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getOne((Wrapper) (new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, code));
            if (onlCgformHead == null) {
                return Result.error("实体不存在");
            }

            if (id.indexOf(",") > 0) {
                String tableName = onlCgformHead.getTableName();
                this.onlCgformFieldService.deleteAutoListById(tableName, id);
            } else {
                this.onlCgformHeadService.deleteOneTableInfo(onlCgformHead.getId(), id);
            }
        } catch (Exception e) {
            log.error("OnlCgformApiController.formEdit()发生异常：" + e.getMessage(), e);
            return Result.error("删除失败");
        }

        return Result.ok("删除成功!");
    }

    @GetMapping({"/getQueryInfo/{code}"})
    public Result<?> getQueryInfo(@PathVariable("code") String code) {
        try {
            List autoListQueryInfo = this.onlCgformFieldService.getAutoListQueryInfo(code);
            return Result.ok(autoListQueryInfo);
        } catch (Exception e) {
            log.error("OnlCgformApiController.getQueryInfo()发生异常：" + e.getMessage(), e);
            return Result.error("查询失败");
        }
    }

    @PostMapping({"/doDbSynch/{code}/{synMethod}"})
    public Result<?> doDbSynch(@PathVariable("code") String code, @PathVariable("synMethod") String synMethod) {
        try {
            long currentTimeMillis = System.currentTimeMillis();
            this.onlCgformHeadService.doDbSynch(code, synMethod);
            log.info("==同步数据库消耗时间" + (System.currentTimeMillis() - currentTimeMillis) + "毫秒");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("同步数据库失败，" + SqlSymbolUtil.getMessage(e));
        }

        return Result.ok("同步数据库成功!");
    }

    @GetMapping({"/exportXls/{code}"})
    public void exportXls(@PathVariable("code") String code, HttpServletRequest request, HttpServletResponse response) {
        OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(code);
        if (onlCgformHead != null) {
            String tableTxt = onlCgformHead.getTableTxt();
            String paramsStr = request.getParameter("paramsStr");
            Object hashMap = new HashMap();
            String s = null;
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                try {
                    s = URLDecoder.decode(paramsStr, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    log.error(e.getMessage(), e);
                }

                if (s != null) {
                    hashMap = (Map) JSONObject.parseObject(s, Map.class);
                }
            }

            ((Map) hashMap).put("pageSize", -521);
            Map autolistPage = this.onlCgformFieldService.queryAutolistPage(onlCgformHead.getTableName(), onlCgformHead.getId(), (Map) hashMap, (List) null);
            List fieldList = (List) autolistPage.get("fieldList");
            List records = (List) autolistPage.get("records");
            List arrayList = new ArrayList();
            String selections = ((Map) hashMap).get("selections") == null ? null : ((Map) hashMap).get("selections").toString();
            List list;
            if (oConvertUtils.isNotEmpty(selections)) {
                list = Arrays.asList(selections.split(","));
                List finalVar1 = list;
                arrayList = (List) ((List<Map>) records).stream().filter((record) -> {
                    return finalVar1.contains(record.get("id"));
                }).collect(Collectors.toList());
            } else {
                if (records == null) {
                    records = new ArrayList();
                }

                ((List) arrayList).addAll((Collection) records);
            }

            ConverterUtil.converter(1, (List) arrayList, fieldList);

            try {
                this.onlCgformHeadService.executeEnhanceExport(onlCgformHead, (List) arrayList);
            } catch (BusinessException e) {
                log.error("导出java增强处理出错", e.getMessage());
            }

            list = this.getExcelExportEntity(fieldList, "id");
            String[] strings;
            if (onlCgformHead.getTableType() == 2 && oConvertUtils.isEmpty(((Map) hashMap).get("exportSingleOnly"))) {
                String subTableStr = onlCgformHead.getSubTableStr();
                if (oConvertUtils.isNotEmpty(subTableStr)) {
                    strings = subTableStr.split(",");
                    String[] strings1 = strings;
                    int length = strings.length;

                    for (int i = 0; i < length; ++i) {
                        String s1 = strings1[i];
                        this.excelExport(s1, (Map) hashMap, (List) arrayList, list);
                    }
                }
            }

            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams((String) null, tableTxt), list, (Collection) arrayList);
            strings = null;

            try {
                response.setContentType("application/x-msdownload;charset=utf-8");
                String checkBrowse = BrowserUtils.checkBrowse(request);
                String tableText = onlCgformHead.getTableTxt() + "-v" + onlCgformHead.getTableVersion();
                if ("MSIE".equalsIgnoreCase(checkBrowse.substring(0, 4))) {
                    response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(tableText, "UTF-8") + ".xls");
                } else {
                    String s1 = new String(tableText.getBytes("UTF-8"), "ISO8859-1");
                    response.setHeader("content-disposition", "attachment;filename=" + s1 + ".xls");
                }

                ServletOutputStream outputStream = response.getOutputStream();
                workbook.write(outputStream);
                response.flushBuffer();
            } catch (Exception e) {
                log.error("--通过流的方式获取文件异常--" + e.getMessage(), e);
            }

        }
    }

    @PostMapping({"/importXls/{code}"})
    public Result<?> importXls(@PathVariable("code") String code, HttpServletRequest request, HttpServletResponse response) {
        long currentTimeMillis = System.currentTimeMillis();
        Result result = new Result();
        String s = "";

        try {
            OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(code);
            if (onlCgformHead == null) {
                return Result.error("数据库不存在该表记录");
            }

            LambdaQueryWrapper<OnlCgformField> onlCgformFieldLambdaQueryWrapper = new LambdaQueryWrapper();
            onlCgformFieldLambdaQueryWrapper.eq(OnlCgformField::getCgformHeadId, code);
            List onlCgformFields = this.onlCgformFieldService.list(onlCgformFieldLambdaQueryWrapper);
            String isSingleTableImport = request.getParameter("isSingleTableImport");
            List imageType = SqlSymbolUtil.getImageType(onlCgformFields);
            if (oConvertUtils.isEmpty(isSingleTableImport) && onlCgformHead.getTableType() == 2 && oConvertUtils.isNotEmpty(onlCgformHead.getSubTableStr())) {
                String[] subTableStrs = onlCgformHead.getSubTableStr().split(",");
                int length = subTableStrs.length;

                for (int i = 0; i < length; ++i) {
                    String subTableStr = subTableStrs[i];
                    OnlCgformHead onlCgformHead1 = (OnlCgformHead) this.onlCgformHeadService.getOne((Wrapper) (new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, subTableStr));
                    if (onlCgformHead1 != null) {
                        List onlCgformFields1 = this.onlCgformFieldService.list((Wrapper) (new LambdaQueryWrapper<OnlCgformField>()).eq(OnlCgformField::getCgformHeadId, onlCgformHead1.getId()));
                        List imageTypeText = SqlSymbolUtil.getImageTypeText(onlCgformFields1, onlCgformHead1.getTableTxt());
                        if (imageTypeText.size() > 0) {
                            imageType.addAll(imageTypeText);
                        }
                    }
                }
            }

            JSONObject jsonObject = null;
            String foreignKeys = request.getParameter("foreignKeys");
            if (oConvertUtils.isNotEmpty(foreignKeys)) {
                jsonObject = JSONObject.parseObject(foreignKeys);
            }

            MultipartHttpServletRequest request1 = (MultipartHttpServletRequest) request;
            Map fileMap = request1.getFileMap();
            DataSource dataSource = (DataSource) SpringContextUtils.getApplicationContext().getBean(DataSource.class);
            String connectionType = TableUtil.getConnectionType(dataSource);
            Iterator iterator = fileMap.entrySet().iterator();

            while (true) {
                while (iterator.hasNext()) {
                    Entry entry = (Entry) iterator.next();
                    MultipartFile multipartFile = (MultipartFile) entry.getValue();
                    ImportParams importParams = new ImportParams();
                    importParams.setImageList(imageType);
                    importParams.setDataHanlder((IExcelDataHandler) new ExcelDataHandlerDefaultUtil(onlCgformFields, this.upLoadPath, this.uploadType));
                    List excel = ExcelImportUtil.importExcel(multipartFile.getInputStream(), Map.class, importParams);
                    if (excel != null) {
                        Object object = "";
                        ArrayList arrayList = new ArrayList();

                        Map map;
                        for (Iterator iterator1 = excel.iterator(); iterator1.hasNext(); map.put("$mainTable$id", object)) {
                            map = (Map) iterator1.next();
                            boolean b = false;
                            Set set = map.keySet();
                            HashMap hashMap = new HashMap();
                            Iterator iterator2 = set.iterator();

                            String s1;
                            while (iterator2.hasNext()) {
                                s1 = (String) iterator2.next();
                                if (s1.indexOf("$subTable$") == -1) {
                                    if (s1.indexOf("$mainTable$") != -1 && oConvertUtils.isNotEmpty(map.get(s1).toString())) {
                                        b = true;
                                        object = this.getIdWorkerId1(onlCgformHead, dataSource, connectionType);
                                    }

                                    hashMap.put(s1.replace("$mainTable$", ""), map.get(s1));
                                }
                            }

                            if (b) {
                                hashMap.put("id", object);
                                arrayList.add(hashMap);
                                object = hashMap.get("id");
                            }

                            if (jsonObject != null) {
                                iterator2 = jsonObject.keySet().iterator();

                                while (iterator2.hasNext()) {
                                    s1 = (String) iterator2.next();
                                    System.out.println(s1 + "=" + jsonObject.getString(s1));
                                    hashMap.put(s1, jsonObject.getString(s1));
                                }
                            }
                        }

                        if (arrayList == null || arrayList.size() == 0) {
                            result.setSuccess(false);
                            result.setMessage("导入失败，匹配的数据条数为零!");
                            return result;
                        }

                        this.onlCgformSqlService.saveBatchOnlineTable(onlCgformHead, onlCgformFields, arrayList);
                        if (oConvertUtils.isEmpty(isSingleTableImport) && onlCgformHead.getTableType() == 2 && oConvertUtils.isNotEmpty(onlCgformHead.getSubTableStr())) {
                            String[] subTableStrs = onlCgformHead.getSubTableStr().split(",");
                            int length = subTableStrs.length;

                            for (int i = 0; i < length; ++i) {
                                String subTableStr = subTableStrs[i];
                                OnlCgformHead onlCgformHead1 = (OnlCgformHead) this.onlCgformHeadService.getOne((Wrapper) (new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, subTableStr));
                                if (onlCgformHead1 != null) {
                                    LambdaQueryWrapper<OnlCgformField> onlCgformFieldLambdaQueryWrapper1 = new LambdaQueryWrapper();
                                    onlCgformFieldLambdaQueryWrapper1.eq(OnlCgformField::getCgformHeadId, onlCgformHead1.getId());
                                    List onlCgformFields1 = this.onlCgformFieldService.list(onlCgformFieldLambdaQueryWrapper1);
                                    ArrayList arrayList1 = new ArrayList();
                                    String tableTxt = onlCgformHead1.getTableTxt();
                                    Iterator iterator1 = excel.iterator();

                                    while (iterator1.hasNext()) {
                                        Map map1 = (Map) iterator1.next();
                                        boolean b = false;
                                        HashMap hashMap = new HashMap();
                                        Iterator iterator2 = onlCgformFields1.iterator();

                                        while (iterator2.hasNext()) {
                                            OnlCgformField onlCgformField = (OnlCgformField) iterator2.next();
                                            String mainTable = onlCgformField.getMainTable();
                                            String mainField = onlCgformField.getMainField();
                                            boolean b1 = onlCgformHead.getTableName().equals(mainTable) && oConvertUtils.isNotEmpty(mainField);
                                            String dbFieldTxt = tableTxt + "_" + onlCgformField.getDbFieldTxt();
                                            if (b1) {
                                                hashMap.put(onlCgformField.getDbFieldName(), map1.get("$mainTable$" + mainField));
                                            }

                                            Object subTable = map1.get("$subTable$" + dbFieldTxt);
                                            if (null != subTable && oConvertUtils.isNotEmpty(subTable.toString())) {
                                                b = true;
                                                hashMap.put(onlCgformField.getDbFieldName(), subTable);
                                            }
                                        }

                                        if (b) {
                                            hashMap.put("id", this.getIdWorkerId1(onlCgformHead1, dataSource, connectionType));
                                            arrayList1.add(hashMap);
                                        }
                                    }

                                    if (arrayList1.size() > 0) {
                                        this.onlCgformSqlService.saveBatchOnlineTable(onlCgformHead1, onlCgformFields1, arrayList1);
                                    }
                                }
                            }
                        }

                        s = "文件导入成功！";
                    } else {
                        s = "识别模版数据错误";
                        log.error(s);
                    }
                }

                result.setSuccess(true);
                result.setMessage("导入成功!");
                break;
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            log.error(e.getMessage(), e);
        }

        log.info("=====online导入数据完成,耗时:" + (System.currentTimeMillis() - currentTimeMillis) + "毫秒=====");
        return result;
    }

    @PostMapping({"/doButton"})
    public Result<?> doButton(@RequestBody JSONObject jsonObject) {
        String formId = jsonObject.getString("formId");
        String dataId = jsonObject.getString("dataId");
        String buttonCode = jsonObject.getString("buttonCode");
        JSONObject uiFormData = jsonObject.getJSONObject("uiFormData");

        try {
            this.onlCgformHeadService.executeCustomerButton(buttonCode, formId, dataId);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("执行失败!");
        }

        return Result.ok("执行成功!");
    }

    public Object getIdWorkerId1(OnlCgformHead onlCgformHead, DataSource dataSource, String connectionType) throws SQLException, DBException {
        Object object = null;
        String idType = onlCgformHead.getIdType();
        String idSequence = onlCgformHead.getIdSequence();
        if (oConvertUtils.isNotEmpty(idType) && "UUID".equalsIgnoreCase(idType)) {
            object = SqlSymbolUtil.getIdWorkerId();
        } else {
            PostgreSQLSequenceMaxValueIncrementer postgreSsqlSequenceMaxValueIncrementer;
            OracleSequenceMaxValueIncrementer oracleSequenceMaxValueIncrementer;
            if (oConvertUtils.isNotEmpty(idType) && "NATIVE".equalsIgnoreCase(idType)) {
                if (oConvertUtils.isNotEmpty(connectionType) && "oracle".equalsIgnoreCase(connectionType)) {
                    oracleSequenceMaxValueIncrementer = new OracleSequenceMaxValueIncrementer(dataSource, "HIBERNATE_SEQUENCE");

                    try {
                        object = oracleSequenceMaxValueIncrementer.nextLongValue();
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                } else if (oConvertUtils.isNotEmpty(connectionType) && "postgres".equalsIgnoreCase(connectionType)) {
                    postgreSsqlSequenceMaxValueIncrementer = new PostgreSQLSequenceMaxValueIncrementer(dataSource, "HIBERNATE_SEQUENCE");

                    try {
                        object = postgreSsqlSequenceMaxValueIncrementer.nextLongValue();
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                } else {
                    object = null;
                }
            } else if (oConvertUtils.isNotEmpty(idType) && "SEQUENCE".equalsIgnoreCase(idType)) {
                if (oConvertUtils.isNotEmpty(connectionType) && "oracle".equalsIgnoreCase(connectionType)) {
                    oracleSequenceMaxValueIncrementer = new OracleSequenceMaxValueIncrementer(dataSource, idSequence);

                    try {
                        object = oracleSequenceMaxValueIncrementer.nextLongValue();
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                } else if (oConvertUtils.isNotEmpty(connectionType) && "postgres".equalsIgnoreCase(connectionType)) {
                    postgreSsqlSequenceMaxValueIncrementer = new PostgreSQLSequenceMaxValueIncrementer(dataSource, idSequence);

                    try {
                        object = postgreSsqlSequenceMaxValueIncrementer.nextLongValue();
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                } else {
                    object = null;
                }
            } else {
                object = SqlSymbolUtil.getIdWorkerId();
            }
        }

        return object;
    }


    private List<ExcelExportEntity> getExcelExportEntity(List<OnlCgformField> onlCgformFields, String s) {
        ArrayList arrayList = new ArrayList();

        for (int i = 0; i < onlCgformFields.size(); ++i) {
            if ((null == s || !s.equals(((OnlCgformField) onlCgformFields.get(i)).getDbFieldName())) && ((OnlCgformField) onlCgformFields.get(i)).getIsShowList() == 1) {
                String dbFieldName = ((OnlCgformField) onlCgformFields.get(i)).getDbFieldName();
                ExcelExportEntity excelExportEntity = new ExcelExportEntity(((OnlCgformField) onlCgformFields.get(i)).getDbFieldTxt(), dbFieldName);
                if ("image".equals(((OnlCgformField) onlCgformFields.get(i)).getFieldShowType())) {
                    excelExportEntity.setType(2);
                    excelExportEntity.setExportImageType(3);
                    excelExportEntity.setImageBasePath(this.upLoadPath);
                    excelExportEntity.setHeight(50.0D);
                    excelExportEntity.setWidth(60.0D);
                } else {
                    int dbLength = ((OnlCgformField) onlCgformFields.get(i)).getDbLength() == 0 ? 12 : (((OnlCgformField) onlCgformFields.get(i)).getDbLength() > 30 ? 30 : ((OnlCgformField) onlCgformFields.get(i)).getDbLength());
                    if ("date".equals(((OnlCgformField) onlCgformFields.get(i)).getFieldShowType())) {
                        excelExportEntity.setFormat("yyyy-MM-dd");
                    } else if ("datetime".equals(((OnlCgformField) onlCgformFields.get(i)).getFieldShowType())) {
                        excelExportEntity.setFormat("yyyy-MM-dd HH:mm:ss");
                    }

                    if (dbLength < 10) {
                        dbLength = 10;
                    }

                    excelExportEntity.setWidth((double) dbLength);
                }

                arrayList.add(excelExportEntity);
            }
        }

        return arrayList;
    }

    private void excelExport(String s, Map<String, Object> map, List<Map<String, Object>> mapList, List<ExcelExportEntity> excelExportEntities) {
        OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getOne((Wrapper) (new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, s));
        LambdaQueryWrapper<OnlCgformField> onlCgformFieldLambdaQueryWrapper = new LambdaQueryWrapper();
        onlCgformFieldLambdaQueryWrapper.eq(OnlCgformField::getCgformHeadId, onlCgformHead.getId());
        onlCgformFieldLambdaQueryWrapper.orderByAsc(OnlCgformField::getOrderNum);
        List onlCgformFields = this.onlCgformFieldService.list(onlCgformFieldLambdaQueryWrapper);
        String s1 = "";
        String s2 = "";
        Iterator iterator = onlCgformFields.iterator();

        while (iterator.hasNext()) {
            OnlCgformField onlCgformField = (OnlCgformField) iterator.next();
            if (oConvertUtils.isNotEmpty(onlCgformField.getMainField())) {
                s1 = onlCgformField.getMainField();
                s2 = onlCgformField.getDbFieldName();
                break;
            }
        }

        ExcelExportEntity excelExportEntity = new ExcelExportEntity(onlCgformHead.getTableTxt(), s);
        excelExportEntity.setList(this.getExcelExportEntity(onlCgformFields, "id"));
        excelExportEntities.add(excelExportEntity);

        for (int i = 0; i < mapList.size(); ++i) {
            map.put(s2, ((Map) mapList.get(i)).get(s1));
            String sql = SqlSymbolUtil.getSelectSql(onlCgformHead.getTableName(), onlCgformFields, map);
            log.info("-----------动态列表查询子表sql》》" + sql);
            List listData = this.onlCgformHeadService.queryListData(sql);
            ConverterUtil.converter(1, listData, onlCgformFields);
            ((Map) mapList.get(i)).put(s, SqlSymbolUtil.getMapList(listData));
        }

    }

    @GetMapping({"/checkOnlyTable"})
    public Result<?> checkOnlyTable(@RequestParam("tbname") String tbname, @RequestParam("id") String id) {
        if (oConvertUtils.isEmpty(id)) {
            if (TableUtil.isTableExist(tbname)) {
                return Result.ok(-1);
            }
        } else {
            OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(id);
            if (!tbname.equals(onlCgformHead.getTableName()) && TableUtil.isTableExist(tbname)) {
                return Result.ok(-1);
            }
        }

        return Result.ok(1);
    }

    @PostMapping({"/codeGenerate"})
    public Result<?> codeGenerate(@RequestBody JSONObject jsonObject) {
        OnlGenerateModel onlGenerateModel = (OnlGenerateModel) JSONObject.parseObject(jsonObject.toJSONString(), OnlGenerateModel.class);
        List list = null;

        try {
            if ("1".equals(onlGenerateModel.getJformType())) {
                list = this.onlCgformHeadService.generateCode(onlGenerateModel);
            } else {
                list = this.onlCgformHeadService.generateOneToMany(onlGenerateModel);
            }

            return Result.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    @GetMapping({"/downGenerateCode"})
    public void downGenerateCode(@RequestParam("fileList") List<String> fileList, HttpServletRequest request, HttpServletResponse response) {
        List fileList1 = (List) fileList.stream().filter((field) -> {
            return field.indexOf("src/main/java") == -1 && field.indexOf("src%5Cmain%5Cjava") == -1;
        }).collect(Collectors.toList());
        if (fileList != null && (fileList1 == null || fileList1.size() <= 0)) {
            String s = "生成代码_" + System.currentTimeMillis() + ".zip";
            final String s1 = "/opt/temp/codegenerate/" + s;
            File file = FilesGeneratedUtil.getFile(fileList, s1);
            if (file.exists()) {
                response.setContentType("application/force-download");
                response.addHeader("Content-Disposition", "attachment;fileName=" + s);
                byte[] bytes = new byte[1024];
                FileInputStream fileInputStream = null;
                BufferedInputStream bufferedInputStream = null;

                try {
                    fileInputStream = new FileInputStream(file);
                    bufferedInputStream = new BufferedInputStream(fileInputStream);
                    ServletOutputStream servletOutputStream = response.getOutputStream();

                    for (int i = bufferedInputStream.read(bytes); i != -1; i = bufferedInputStream.read(bytes)) {
                        servletOutputStream.write(bytes, 0, i);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bufferedInputStream != null) {
                        try {
                            bufferedInputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    if (fileInputStream != null) {
                        try {
                            fileInputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    class NamelessClass_1 extends Thread {
                        NamelessClass_1() {
                        }

                        @Override
                        public void run() {
                            try {
                                Thread.sleep(10000L);
                                FileUtil.del(s1);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                        }
                    }

                    (new NamelessClass_1()).start();
                }
            }

        } else {
            log.error(" fileList 不合法！！！", fileList);
        }
    }

    @GetMapping({"/getTreeData/{code}"})
    //@PermissionData
    public Result<Map<String, Object>> getTreeData(@PathVariable("code") String code, HttpServletRequest request) {
        Result result = new Result();
        OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(code);
        if (onlCgformHead == null) {
            result.error500("实体不存在");
            return result;
        } else {
            try {
                String tableName = onlCgformHead.getTableName();
                String treeIdField = onlCgformHead.getTreeIdField();
                String treeParentIdField = onlCgformHead.getTreeParentIdField();
                ArrayList arrayList = Lists.newArrayList(new String[]{treeIdField, treeParentIdField});
                Map parameterMap = SqlSymbolUtil.getParameterMap(request);
                String s = null;
                if (parameterMap.get(treeIdField) != null) {
                    s = parameterMap.get(treeIdField).toString();
                }

                if (parameterMap.get(treeParentIdField) != null && !"0".equals(parameterMap.get(treeParentIdField))) {
                    parameterMap.put("pageSize", -521);
                    parameterMap.put(treeParentIdField, parameterMap.get(treeParentIdField));
                } else {
                    parameterMap.put(treeParentIdField, "0");
                }

                parameterMap.put(treeIdField, (Object) null);
                Map map = this.onlCgformFieldService.queryAutolistPage(tableName, code, parameterMap, arrayList);
                if (parameterMap.get(treeParentIdField) != null) {
                    String treeParentIdFieldStr = parameterMap.get(treeParentIdField).toString();
                    if (!"0".equals(parameterMap.get(treeParentIdField)) && map.get("total") != null && Integer.parseInt(map.get("total").toString()) == 0 && s != null && "1".equals(s)) {
                        this.onlCgformFieldService.updateTreeNodeNoChild(tableName, treeIdField, treeParentIdFieldStr);
                    }
                }

                this.recordsEnhance(onlCgformHead, map);
                result.setResult(map);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                result.error500("数据库查询失败" + e.getMessage());
            }

            return result;
        }
    }

    private void recordsEnhance(OnlCgformHead onlCgformHead, Map<String, Object> map) throws BusinessException {
        List records = (List) map.get("records");
        this.onlCgformHeadService.executeEnhanceList(onlCgformHead, "query", records);
    }

    @PostMapping({"/crazyForm/{name}"})
    public Result<?> addCrazyForm(@PathVariable("name") String name, @RequestBody JSONObject jsonObject) {
        Result result = new Result();

        try {
            String workerId = SqlSymbolUtil.getIdWorkerId();
            jsonObject.put("id", workerId);
            this.onlCgformHeadService.addCrazyFormData(name, jsonObject);
            result.setResult(workerId);
            result.setMessage("保存成功");
            return result;
        } catch (Exception e) {
            log.error("OnlCgformApiController.formAddForDesigner()发生异常：" + e.getMessage(), e);
            return Result.error("保存失败");
        }
    }

    @PutMapping({"/crazyForm/{name}"})
    public Result<?> updateCrazyForm(@PathVariable("name") String name, @RequestBody JSONObject jsonObject) {
        try {
            this.onlCgformHeadService.editCrazyFormData(name, jsonObject);
        } catch (Exception e) {
            log.error("OnlCgformApiController.formEditForDesigner()发生异常：" + e.getMessage(), e);
            return Result.error("保存失败");
        }

        return Result.ok("保存成功!");
    }

    @GetMapping({"/getErpColumns/{code}"})
    public Result<Map<String, Object>> getErpColumns(@PathVariable("code") String code, HttpServletRequest request) {
        Result result = new Result();
        OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(code);
        if (onlCgformHead == null) {
            result.error500("实体不存在");
            return result;
        } else {
            HashMap hashMap = new HashMap();
            OnlineConfigModel onlineConfigModel = this.onlineService.queryOnlineConfig(onlCgformHead);
            hashMap.put("main", onlineConfigModel);
            if ("erp".equals(onlCgformHead.getThemeTemplate()) && onlCgformHead.getTableType() == 2) {
                String subTableStr = onlCgformHead.getSubTableStr();
                if (oConvertUtils.isNotEmpty(subTableStr)) {
                    ArrayList arrayList = new ArrayList();
                    String[] subTableStrs = subTableStr.split(",");
                    int length = subTableStrs.length;

                    for (int i = 0; i < length; ++i) {
                        String subTableStr1 = subTableStrs[i];
                        OnlCgformHead onlCgformHead1 = (OnlCgformHead) this.onlCgformHeadService.getOne((Wrapper) (new LambdaQueryWrapper<OnlCgformHead>()).eq(OnlCgformHead::getTableName, subTableStr1));
                        if (onlCgformHead1 != null) {
                            arrayList.add(this.onlineService.queryOnlineConfig(onlCgformHead1));
                        }
                    }

                    if (arrayList.size() > 0) {
                        hashMap.put("subList", arrayList);
                    }
                }
            }

            result.setResult(hashMap);
            result.setSuccess(true);
            return result;
        }
    }

    @GetMapping({"/getErpFormItem/{code}"})
    public Result<?> getErpFormItem(@PathVariable("code") String code, HttpServletRequest request) {
        OnlCgformHead onlCgformHead = (OnlCgformHead) this.onlCgformHeadService.getById(code);
        if (onlCgformHead == null) {
            Result.error("表不存在");
        }

        Result result = new Result();
        JSONObject jsonObject = this.onlineService.queryOnlineFormObj(onlCgformHead);
        result.setResult(jsonObject);
        return result;
    }

    @GetMapping({"/querySelectOptions"})
    public Result<List<TreeModel>> querySelectOptions(@ModelAttribute LinkDown linkDown) {
        Result result = new Result();
        List dataListByLinkDown = this.onlCgformFieldService.queryDataListByLinkDown(linkDown);
        result.setResult(dataListByLinkDown);
        result.setSuccess(true);
        return result;
    }
}
